package com.le.tester.tip;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * createTime：2022/2/15 10:01
 * description：volatile synchronized
 */
public class Counter {
    //private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
    private volatile int a = 0;
    private volatile int value;
    private static AtomicInteger atomicInteger = new AtomicInteger();


    public final int addAndGet(int delta) {
        for (; ; ) {
            int current = this.get();
            int next = current + delta;
            if (compareAndSet(current, next))
                return next;
        }

    }

    //无锁计数
    public final boolean compareAndSet(int expect, int update) {
        //return UNSAFE.compareAndSwapInt(this, 0, 0, 0);
        return false;
    }

    public synchronized int incrementAndGet(int number) {
        this.a += number;
        return a;
    }

    public synchronized int get() {
        return a;
    }

    public synchronized int compareAndSwap(int expect, int newValue) {
        int old = this.a;
        if (old == expect) {
            this.a = newValue;
        }
        return old;
    }

    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                int a1 = counter.incrementAndGet(1);
                System.out.println("for 1 a1 is " + a1);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                int a2 = counter.incrementAndGet(1);
                System.out.println("for 2 a2 is " + a2);
            }
        });

        t1.start();
        t2.start();
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e.getMessage());
//        }
//        System.out.println("result is " + counter.get());
    }
}
